import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { courseGet } from "../../api/course";

const courseSlice = createSlice({
  name: "course",
  initialState: {
    list: [],
  },
  reducers: {
    changeCourseList(state, action) {
      console.log("课程action", action);
      state.list = action.payload; //此处的payload是触发action时传递的数据包
    },
  },
  // extraReducers的作用是检测异步action的执行过程
  extraReducers: (builder) => {
    builder
      .addCase(getCourseListAction.pending, (state) => {
        console.log("异步action的pedding状态");
      })
      .addCase(getCourseListAction.fulfilled, (state, action) => {
        console.log("fulfilled状态", action);
        state.list = action.payload;
      })
      .addCase(getCourseListAction.rejected, () => {
        console.log("异步action的rejected失败状态");
      });
  },
});

//创建异步action
export const getCourseListAction = createAsyncThunk(
  "course/changeCourseList",
  async () => {
    let res = await courseGet();
    return res.data.results;
  }
);

export const { changeCourseList } = courseSlice.actions;
export default courseSlice.reducer;
